/*
 * @Author: delin66
 * @Date: 2024-12-01 18:04:42
 * @LastEditors: delin66
 * @LastEditTime: 2025-04-12 16:05:36
 * @Descripttion: 
 */
import { ElMessage, ElMessageBox } from 'element-plus'; 
import { createRouter, createWebHashHistory } from 'vue-router'; 
import routes from './routes'; 
import { getRoleKeys, getToken } from '@/utils/storage'; 

const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL), // 创建带有哈希历史记录的路由器实例
  routes, 
});

router.beforeEach(async (to, from) => {
 
  window.scrollTo(0, 0);
  const token = getToken(); 
  // 设置需要登录才能进入页面
  console.log("权限校验")
  if (to.meta.auth === true) {
    if (token) {
      // 设置只有企业人员才能进入的页面
      if (to.meta.isEmployee) {
        const roleKeys = getRoleKeys(); 
        if (roleKeys.includes('enterprise') || roleKeys.includes('admin')) {
          return true; 
        } else {
          ElMessage.warning('该界面只有企业人员才能进入！'); // 显示警告消息
          return false; // 阻止进入页面
        }
      }
      return true; 
    } else {
      const res = await ElMessageBox.confirm('该界面需要登录才能访问，是否去登录？', '登录提示：', {
        confirmButtonText: '去登录',
        cancelButtonText: '取消', 
      })
        .then(() => {
          return {
            name: 'login',
            query: {
              redirect: to.fullPath, 
            },
          };
        })
        .catch(() => {
          return from.fullPath; 
        });
      return res; 
    }
  }
  return true
});

export default router;